package org.monkey.service;

import lombok.extern.slf4j.Slf4j;
import org.monkey.service.impl.UserServiceImpl;
import org.monkey.spring.BeanPostProcessor;
import org.monkey.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component("uuBeanPostProcessor")
@Slf4j
public class UuBeanPostProcessor implements BeanPostProcessor
{
    /**
     *
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if (beanName.equals("userService")) {
            log.info("initialization before {}", beanName);
            ((UserServiceImpl)bean).setName("UU's good");
        }

        return bean;
    }

    /**
     * 在返回第一个接口的实例的代理对象
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        // 匹配 切点
        if (beanName.equalsIgnoreCase("aopImpl")) {
            log.info("initialization after beanName: {}, bean {}" , beanName, bean);
            log.info("getInterfaces {}", bean.getClass().getInterfaces());
            Object proxyInstance = Proxy.newProxyInstance(UuBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(),
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            log.info("执行代理逻辑"); // 找切点
                            Object invoke = method.invoke(bean, args);
                            return invoke;
                        }
                    });
            return proxyInstance;
        }
        return bean;
    }
}
